$(function() {

    'use strict';

    var wrap = $('.g-wrap'),
        longNode = $('.g-long'),
        bNode = $('.g-wrap-b'),
        tNode = $('.g-wrap-t'),
        cNode = $('.g-wrap-c'),
        isIOS = navigator.userAgent.indexOf('iPhone') > 0 ? true : false,
        dir = isIOS ? 1 : -1,
        st = null;


    if (!isIOS) {
        // $('.btn').addClass('active')
    }
    $(window).resize(function() {
        bNode.height($(window).width() / 320 * 1007);
        cNode.height($(window).width() / 320 * 1055);
        tNode.height($(window).width() / 320 * 1475);
    });

    $(window).resize();


    /**
     * 分享模块
     * @return {[type]} [description]
     */
    (function() {

        var shareInfo = {
            shareTitle: '穿越云霄·谕见你',
            descContent: '《天谕》6.19超人气开放性测试，你我终将谕见。',
            shareTimeTitle: '穿越云霄·谕见你',
            imgUrl: $('#shareData').data('src'),
            lineLink: window.location.href
        };

        // Share yixin
        var onYixinBridgeReady = function() {

            YixinJSBridge.on('menu:share:appmessage', function() {
                YixinJSBridge.invoke('sendAppMessage', {
                    img_width: '300',
                    img_height: '300',
                    img_url: shareInfo.imgUrl,
                    link: shareInfo.lineLink,
                    desc: shareInfo.descContent,
                    title: shareInfo.shareTitle
                }, function(res) {
                    nie.config.stats.url.add("1234/index_0615.html?click=index", "天谕大世界");
                    $('.share-pop').fadeOut();
                    window.location = 'http://tianyu.163.com/';
                });
            });

            YixinJSBridge.on('menu:share:timeline', function() {
                YixinJSBridge.invoke('shareTimeline', {
                    img_width: '300',
                    img_height: '300',
                    img_url: shareInfo.imgUrl,
                    link: shareInfo.lineLink,
                    desc: shareInfo.shareTimeTitle,
                    title: shareInfo.shareTimeTitle
                }, function(res) {
                    nie.config.stats.url.add("1234/index_0615.html?click=index", "天谕大世界");
                    $('.share-pop').fadeOut();
                    window.location = 'http://tianyu.163.com/';
                });
            });
        };

        if (document.addEventListener) {
            document.addEventListener('YixinJSBridgeReady', onYixinBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('YixinJSBridgeReady', onYixinBridgeReady);
            document.attachEvent('onYixinJSBridgeReady', onYixinBridgeReady);
        }

        // Share weixin
        wx.config(wx_conf);

        wx.ready(function() {

            wx.onMenuShareTimeline({
                title: shareInfo.shareTimeTitle,
                link: shareInfo.lineLink,
                imgUrl: shareInfo.imgUrl,
                success: function() {
                    nie.config.stats.url.add("1234/index_0615.html?click=index", "天谕大世界");
                    $('.share-pop').fadeOut();
                    window.location = 'http://tianyu.163.com/';
                },
                cancel: function() {}
            });

            wx.onMenuShareAppMessage({
                title: shareInfo.shareTitle,
                desc: shareInfo.descContent,
                link: shareInfo.lineLink,
                imgUrl: shareInfo.imgUrl,
                success: function() {
                    nie.config.stats.url.add("1234/index_0615.html?click=index", "天谕大世界");
                    $('.share-pop').fadeOut();
                    window.location = 'http://tianyu.163.com/';
                },
                cancel: function() {}
            });
        });
    }());

    /**
     * imgloader
     * @type {Object}
     */
    var imgLoader = {

        _srcs: [],
        _onLoaded: null,
        _onLoading: null,

        load: function() {

            var srcs = this._srcs,
                l = srcs.length,
                loadCount = 0,
                that = this,
                tmp,
                i;

            function onImgLoad() {
                if (++loadCount === l) {
                    that._onLoaded && that._onLoaded();
                } else {
                    that._onLoading && that._onLoading(Math.floor(loadCount / l * 100));
                }
            }

            if (!l) {
                that._onLoaded && that._onLoaded();
                return this;
            }

            for (i = l; i--;) {
                tmp = new Image();
                tmp.src = srcs[i];
                tmp.onload = onImgLoad;
            }

            return this;
        },

        init: function(arrSrcs, onLoaded, onLoading) {
            this._srcs = arrSrcs.slice(0);
            this._onLoaded = onLoaded;
            this._onLoading = onLoading;
            return this;
        }
    };


    var EMPFN = function() {},
        defaultParam = {
            shake: function() {},
            rotate: function() {}
        };


    /**
     * 将新对象合并到老对象中，不合并已有字段，并返回老对象
     * @param  {object} o 老对象
     * @param  {object} n 新对象
     * @return {object}   合并后的老对象
     */

    function merge(o, n) {
        for (var i in n) {
            if (!o.hasOwnProperty(n[i])) o[i] = n[i];
        }
        return o;
    }


    /**
     *  重力感应类
     * @param {[type]} options [description]
     */
    function DeviceMotion(options) {
        this.init(options);
    }

    DeviceMotion.prototype = {
        // 摇一摇阈值
        SHAKE_THRESHOLD: 3000,
        // 取得数据间隔
        _GET_DATA_INTERVAL: 40,
        init: function(options) {
            var self = this;
            self.params = options || {};

            self.params = merge(defaultParam, self.params);

            // 是否开始获取数据
            self._getData = false;
            // 保存上一次的motion
            self.last = {};
            // 保存本次motion
            self.cur = {
                acceleration: {},
                accelerationIncludingGravity: {},
                rotationRate: {}
            }


            // 初始化临时参数
            self.__param = {
                shakeParam: {}
            };

            if (window.DeviceMotionEvent) {
                window.addEventListener('devicemotion', function(event) {
                    self.onDeviceMotion.call(self, event)
                });

                self._startCount();
            } else {
                alert('your browser is not support devicemotion event!');
            }
        },
        /**
         * 开始计时去取数据
         * @return {[type]} [description]
         */
        _startCount: function() {
            var self = this;

            self._timer = setInterval(function() {
                self._getData = true;
                self.tilt.call(self);
            }, self._GET_DATA_INTERVAL)
        },
        destory: function() {
            var self = this;

            clearInterval(self._timer);

        },
        // 倾斜
        tilt: function() {
            var self = this,
                AIG = self.cur.accelerationIncludingGravity;

            self.params.tilt.call(self, AIG)
        },
        _setDeviceMotionData: function(motion) {
            var self = this;

            self.last = self.cur;

            self.cur = motion;

            self.acceleration = motion.acceleration;
            self.accelerationIG = motion.accelerationIncludingGravity;
            self.rotationRate = motion.rotationRate;
        },
        onDeviceMotion: function(event) {
            var self = this;

            if (self._getData) {
                self._getData = false;
                self._setDeviceMotionData(event)
            }

        }
    }


    var margin = {
        'ios5': [2700, 2200, 1700, 1164, 700, 350],
        'ios6': [3100, 2400, 1900, 1364, 700, 350],
        'ios6p': [3400, 2700, 2200, 1664, 900, 550]
    }

    if ($(window).width() <= 320) {
        margin = margin['ios5'];
    } else if ($(window).width() <= 375) {
        margin = margin['ios6'];
    } else if ($(window).width() <= 414) {
        margin = margin['ios6p'];
    } else {
        margin = margin['ios5'];
    }

    function troggleActive(st) {
        // print(st)
        if (!isIOS) {
            // return;
        }

        if (st > 2160) {
            // print('t'+st)
            bNode.addClass('active');
            tNode.removeClass('active');
            cNode.removeClass('active');

            if (!bNode.find('.text-con').hasClass('active')) {
                bNode.find('.text-con').addClass('active')
                bNode.find('.tip').addClass('active')
            }

        } else if (st < 2160 && st > 1100) {
            // print('c'+st)
            bNode.removeClass('active');
            tNode.removeClass('active')
            cNode.addClass('active')



        } else if (st < 1100 && st > 0) {
            // print('t'+st)
            bNode.removeClass('active');
            tNode.addClass('active')
            cNode.removeClass('active')
        }
        // 显示按钮1
        if (st < margin[0]) {
            $('.btn1').addClass('active');
        }

        // 显示按钮2
        if (st < margin[1]) {
            $('.btn2').addClass('active');
        }
        // 显示按钮3
        if (st < margin[2]) {
            $('.btn3').addClass('active');
        }

        // 显示按钮4
        if (st < margin[3]) {
            $('.btn4').addClass('active');
        }

        // 显示按钮5
        if (st < margin[4]) {
            $('.btn5').addClass('active');
        }

        // 显示按钮6
        if (st < margin[5]) {
            $('.btn6').addClass('active');
        }

        // 显示logo
        if (st < 50) {
            $('.logo-text').addClass('active')
        }
    }

    longNode.css({
        'webkitTransform': 'translateY(' + ($(window).height() - longNode.height()) + 'px)'
    });

    var imgList = [],
        imgData = $('#imgData').children();

    for(var i = 0 ; i < imgData.length ; i ++){
        imgList.push(imgData[i].getAttribute('data-src'));
    }


    imgLoader.init(imgList, function() {
        setTimeout(function() {
            new DeviceMotion({
                tilt: function(step) {
                    if (step.z) {
                        st = longNode.offset().top;
                        if ((Math.abs(st) >= longNode.height() - $(window).height() && dir * step.z < 0)) {
                            longNode.css({
                                'webkitTransform': 'translateY(' + $(window).height() - longNode.height() + 'px)'
                            });
                            return;
                        } else if (st >= 0 && dir * step.z > 0) {
                            longNode.css({
                                'webkitTransform': 'translateY(0px)'
                            });
                            return;
                        }
                        // longNode.animate({
                        //     stepValue:dir * step.z
                        // },{
                        //     duration:30,
                        //     step : function(now){
                        //         print(now)
                        //         longNode.css({
                        //             'webkitTransform':'translateY('+(st + now)+'px)'
                        //         });
                        //     }
                        // });

                        longNode.css({
                            'webkitTransform': 'translateY(' + (st + dir * step.z / 0.5) + 'px)'
                        });
                        troggleActive(-st)
                    }
                }
            });

            0 && setInterval(function() {
                st = longNode.offset().top;

                if ((Math.abs(st) >= longNode.height() - $(window).height() && dir * 5 < 0)) {
                    longNode.css('marginTop', $(window).height() - longNode.height());
                    return;
                } else if (st >= 0 && dir * 5 > 0) {
                    longNode.css('marginTop', 0);
                    return;
                }
                longNode.css({
                    'webkitTransform': 'translateY(' + (st + dir * 8) + 'px)'
                });
                /*longNode.animate({
                    step: st + dir * 5
                },{
                    duration : 30,
                    step : function(now){
                        console.log(now);
                    }
                });*/
                troggleActive(-st)
            }, 30);
        }, 8000);


        troggleActive(110000);
    }).load();

    // 分享点击
    $('.btn6').click(function() {
        $('.share-pop').fadeIn();
    })
    $('.share-pop').bind('touchstart', function() {
        $(this).fadeOut();
    });
});